package com.hmall.gateway.filter;

import com.hmall.common.utils.CollUtils;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.function.Consumer;

@Component
@EnableConfigurationProperties(AuthProperties.class)
public class AuthClobalFilter implements GlobalFilter {
    @Autowired
    private AuthProperties authProperties;
    @Autowired
    private JwtTool jwtTool;
    private static final AntPathMatcher ANT_PATH_MATCHER =new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("全局过滤器启动了....");
        //1. 拿到前端的请求路径
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        //2. 注入配置类,得到配置文件中的放行路径-> 匹配路径我们封装一个方法
        boolean result = chickPath(path);
        if (result){
            //匹配放行路径,成功直接放行
            return chain.filter(exchange);
        }
        //匹配失败就解析Token
        List<String> authorization = request.getHeaders().get("authorization");
        //这里authorization是一个list是因为:header可以看做是一个特殊的map,里面的key可以重复;但是实际上不可能有多个token
        if (CollUtils.isEmpty( authorization)){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            //直接返回请求,不再向下传递
            return exchange.getResponse().setComplete();
        }
        String token = authorization.get(0);
        try {
            //验证Token成功将信息转发给微服务
            Long userid = jwtTool.parseToken(token);
            //将解析出来的userid转发下游服务
            exchange.mutate().request(new Consumer<ServerHttpRequest.Builder>() {
                @Override
                public void accept(ServerHttpRequest.Builder builder) {
                    builder.header("user-info",userid.toString());
                }
            });
            return chain.filter(exchange);
        } catch (Exception e) {
            //验证Token失败,返回401
            e.printStackTrace();
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
    }
    private boolean chickPath(String path) {
        List<String> excludePaths = authProperties.getExcludePaths();
        for (String excludePath : excludePaths) {
            if (ANT_PATH_MATCHER.match(excludePath, path)) {
                //匹配成功就放行
                return true;
            }
        }
        //匹配失败就返回false需要拦截验证;
        return false;
    }
}
